package com.xcfw.dorm.config;

import com.xcfw.dorm.entity.NumEnum;
import com.xcfw.dorm.entity.ReturnJson;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;

/**
 * @program: Printer
 * @description: 拦截sql错误
 * @author: Bruse Queen
 * @create: 2018-03-15 16:38
 **/
@ControllerAdvice
@Slf4j
public class MyControllerAdvice {


    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     *
     * @param binder 默认参数
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    }

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     *
     * @param model 默认值
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "Magical Sam");
    }

    /**
     * 数据库异常捕捉处理
     *
     * @param ex 异常信息
     * @return 封装标准参数
     */
    @ResponseBody
    @ExceptionHandler(value = SQLException.class)
    public ReturnJson errorHandler(Exception ex) {
        log.error("It's a SQLException error");
        return new ReturnJson(NumEnum.FAIL.getIndex(), ex.getMessage());
    }

}